<?php

class User extends CActiveRecord
{
	public $pass_repeat;
	public $verifyCode;
	
	const SCENARIO_SIGNUP = 'registration';

	const TYPE_CLIENT = 3;
	const TYPE_SHOP_ADMIN = 2;
	const TYPE_SHOP_MANAGER = 4;
	const TYPE_STAFF_ADMIN = 1;
	const TYPE_STAFF_MANAGER = 5;

	public function rules()
	{
		return array(
			array('email, pass', 'required', 'message' => 'Ведите значение "{attribute}".'),
			array('type', 'required', 'message' => 'Ведите значение "{attribute}".', 'on' => self::SCENARIO_SIGNUP),
			array('type', 'numerical'),
			array('email', 'unique', 'on' => self::SCENARIO_SIGNUP),
			array('email', 'email'),
			array('email, pass', 'length', 'max' => 50, 'message' => 'Длинна поля "{attribute}" не должна привышать 50 cимволов.'),
			array('phone', 'length', 'max' => 255, 'message' => 'Максимальное количество символов для поля "{attribute}" 255.'),
			array('pass_repeat', 'required', 'message' => 'Ведите значение "{attribute}".', 'on' => self::SCENARIO_SIGNUP),
			array('verifyCode', 'captcha', 'allowEmpty' => !extension_loaded('gd'), 'on' => self::SCENARIO_SIGNUP),
			array('pass', 'compare', 'compareAttribute' => 'pass_repeat','on' => self::SCENARIO_SIGNUP)
		);
	}

	public function attributeLabels()
	{
		return array(
			'pass' => 'Пароль',
			'email' => 'Email',
			'phone' => 'Телефон',
			'pass_repeat' => 'Проверочный пароль',
		);
	}

	public function relations()
	{
		return array();
	}

	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{user}}';
	}	

	public function login()
	{
		$ui = new UserIdentity($this->email, $this->pass);
		$ui->authenticate();
		
		if($ui->errorCode === UserIdentity::ERROR_NONE)
		{
			$duration = 3600 * 24 * 30; // 30 days
			Yii::app()->user->login($ui, $duration);
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function loginByHash(User $user)
	{
		$ui = new UserIdentity($user->email, $user->pass);
		$ui->authenticate(true);
	
		if($ui->errorCode === UserIdentity::ERROR_NONE)
		{
			$duration = 3600 * 24 * 30; // 30 days
			Yii::app()->user->login($ui, $duration);
			return true;
		}
		else
		{
			return false;
		}
	}
}